package com.financing.wap.web.controller.api;


import cn.jpush.api.utils.Base64;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.financing.wap.common.CommonConstantUtil;
import com.financing.wap.common.ResultMap;
import com.financing.wap.common.ResultMap.STATUS;
import com.financing.wap.common.Session;
import com.financing.wap.common.SessionUtil;
import com.financing.wap.dto.*;
import com.financing.wap.service.*;
import com.financing.wap.util.*;
import com.financing.wap.web.controller.BaseController;

import io.rong.RongCloud;
import io.rong.models.TokenResult;

import org.apache.commons.collections.list.TreeList;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.InputStream;
import java.io.Reader;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.*;

/**
 * 通用 控制器
 * @author jtl
 *
 */
@Controller("apiCommonController")
@RequestMapping("/api/comm")
public class CommonController extends BaseController {

	private String ctxPath = PropertiesUtils.getValue("ctxPath");

	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private IFpPhoneClientService fpPhoneClientService;
	
	@Autowired
	ICommonService commonService;


	@Autowired
	private IMessageJpushUserPhoneAliasService messageJpushUserPhoneAliasService;

	@Autowired
	private IUserService userService;

	@Autowired
	private IUserWechatService userWehatService;
	
	@Autowired
	private IShopperUserInfoService shopperUserInfoService;

	/**
	 * 新增机构FA
	 * @param request
	 * @return
	 */
	@RequestMapping("goto")
	@ResponseBody
	public ResultMap addCorpFa(HttpServletRequest request,String type,String data){
		ResultMap result = new ResultMap();
		try {
		String url = PropertiesUtils.getValue(type);
		url = MessageFormat.format(url,URLEncoder.encode(data,"utf-8")); 
		url = url + "&ip="+IPUtil.getRemoteHost(request);
		logger.info("goto url: "+url);
		String res = HttpClientUtil.getInstance().doGetRequest(url);
		result.setStatus(STATUS.SUCCESS);
		result.setAttribute("msg", res);
		}catch(Exception e) {
			logger.error("goto error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	
	/**
	 * 获取app版本
	 * @param request
	 * @return
	 */
	@RequestMapping("version")
	@ResponseBody
	public ResultMap version(HttpServletRequest request,String platform){
		ResultMap result = new ResultMap();
		try {
			if(StringUtils.isBlank(platform)){
				platform = "ios";
			}

			FpVersionDTO versionDTO=commonService.getQueryVersionno(platform);
			String version = versionDTO==null?null:versionDTO.getVersionNo();
			if(StringUtil.isNullOrEmptyStr(version)){
				version="4.0.1";
			}
			result.setAttribute("version",version);
			result.setAttribute("downUrl",versionDTO==null?null:versionDTO.getDownUrl());
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("get version error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	/**
	 * 获取app版本
	 * @param request
	 * @return
	 */
	@RequestMapping("introduce")
	@ResponseBody
	public ResultMap introduce(HttpServletRequest request){
		ResultMap result = new ResultMap();
		try {
			String version="https://www.superfa.cn/upload/bann/20160907/1473236064177802452.png?"+System.currentTimeMillis();
			result.setAttribute("introduce",version);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("get introduce error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	
	/**
	 * 设置设备号
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("setJpushAlias")
	@ResponseBody
	public ResultMap setJpushAlias(HttpServletRequest request,HttpServletResponse response,String jpush_alias){
		ResultMap result = new ResultMap();
		logger.info("setJpushAlias begin!");
		try {
			logger.info("setJpushAlias jpush_alias:"+jpush_alias);
			Cookie cookie = new Cookie(Constants.JPUSH_ALIAS, jpush_alias);
			cookie.setMaxAge(60*60*24*15);
			cookie.setPath("/");
			response.addCookie(cookie);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			
		logger.info("setJpushAlias end!");
		}catch(Exception e) {
			logger.error("setJpushAlias error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}


	@RequestMapping("gotoUserShop")
	@ResponseBody
	public ResultMap gotoUserShop(HttpServletRequest request,String type,String data){
		ResultMap result = new ResultMap();
		try {
			String wechatId = (String) SessionUtil.getSession(true).getAttribute(WeixinController.OPENID);
			/*if(StringUtils.isBlank(wechatId)){
				logger.error("goto error wechatId is null:");
				result.setStatus(STATUS.SUCCESS);
				result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
				return result;
			}*/
			JSONObject json = JSON.parseObject(data);
          UserDTO user = SessionUtil.getSession().getUser();
			String loginName = "";
			if(user!=null){
				loginName=user.getLoginName();
			}
			json.put("userMobile", loginName);
			json.put("wechatId",wechatId);
			String url = PropertiesUtils.getValue(type);

			logger.info("goto wechatId: "+wechatId);

			logger.info("goto url: "+json.toJSONString());


			url = MessageFormat.format(url,URLEncoder.encode(json.toJSONString(),"utf-8"));
			url = url + "&ip="+IPUtil.getRemoteHost(request);
			logger.info("goto url: "+url);
			String res = HttpClientUtil.getInstance().doGetRequest(url);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
			result.setAttribute("msg", res);
		}catch(Exception e) {
			logger.error("goto error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	@RequestMapping("gotoUserShopForJpush")
	@ResponseBody
	public ResultMap gotoUserShopForJpush(HttpServletRequest request,String shopId){
		ResultMap result = new ResultMap();
		try {
			// 访问推送
			// 极光推送消息

			logger.info("goto url shopId: "+shopId);

			UserDTO loginUser = new UserDTO();
			loginUser.setLoginName(shopId);
			loginUser = userService.queryUserLoginName(loginUser);

			logger.info("goto url shopId: "+shopId);

			// 根据用户查询出绑定的设备标示
			MessageJpushUserPhoneAliasDTO dto = new MessageJpushUserPhoneAliasDTO();
			dto.setFpUserId(loginUser.getId());
			MessageJpushUserPhoneAliasDTO phoneAlias = messageJpushUserPhoneAliasService.queryMessageJpushUserPhoneAlias(dto);
			if(null != phoneAlias ){
				logger.info("goto url shopId: "+shopId);
				MessageJpushDTO messageJpushDTO = new MessageJpushDTO();

				messageJpushDTO.setFpJpushMsgRec(phoneAlias.getFpJpushAliasShop());
				messageJpushDTO.setFpJpushTitle("金策师");
				messageJpushDTO.setFpJpushContent("您的店铺有新的访客来访，请及时跟进处理");
				messageJpushDTO.setFpJpushRedrict(new String(Base64.encode(PropertiesUtils.getValue("jiGuangPushRedrictShopVisit").getBytes())));
				messageJpushDTO.setFpJpushMsgType("03");// 消息类型 01:系统消息 02:运营推送
				messageJpushDTO.setFpJpushSendType("01");// 推送消息类型  01:实时推送  02:定时推送
				messageJpushDTO.setCreateBy("");
				messageJpushDTO.setCreateDate(new Date());
				messageJpushDTO.setUpdateBy("");
				messageJpushDTO.setFpJpushShopType("0");  //0 客户,1 订单
				messageJpushDTO.setUpdateDate(new Date());
				messageJpushDTO.setFpJpushSource("shop"); //加店铺标识
				messageJpushUserPhoneAliasService.addJpushMessage(messageJpushDTO);
			}
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);
		}catch(Exception e) {
			logger.error("goto error:",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 融云-生成token
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/ryToken")
	@ResponseBody
	public ResultMap ryToken(HttpServletRequest request, HttpServletResponse response){
		ResultMap result = new ResultMap();
		try{
			String faId = null;

			// 微信-授权id
			String wechatId = (String) SessionUtil.getSession(true).getAttribute(WeixinController.OPENID);
			RongCloud rongCloud = RongCloud.getInstance();

			// 当前-用户
			Session session = SessionUtil.getSession();
			UserDTO loginUser = session.getUser();
			if(StringUtils.isNotBlank(wechatId)){
				logger.info(" ryToken wechatId:  " + wechatId);
				String  userId = wechatId;

				//微信信息
				Map<String, Object> certTypeMap  = new HashMap<String, Object>();
				getWechatInfo(wechatId,certTypeMap);

				String name  =  certTypeMap.get("nickname") != null?certTypeMap.get("nickname").toString():"";
				String portraitUri =   certTypeMap.get("portraitUri") != null?certTypeMap.get("portraitUri").toString():"";

				if(certTypeMap.get("wechatUserId") != null ){
					userId = certTypeMap.get("wechatUserId").toString();
				}

				// 获取 Token 方法
				TokenResult userGetTokenResult = rongCloud.user.getToken(userId, name,portraitUri);
				logger.info(" ryToken getToken:  " + userGetTokenResult.toString());
				
				System.out.println("rytoken1========================================================");
				System.out.println("rytoken:"+userGetTokenResult.getToken());
				System.out.println("userId:"+userId);
				System.out.println("name:"+name);
				System.out.println("portraitUri:"+portraitUri);
				System.out.println(userGetTokenResult.getErrorMessage());
				
				result.setAttribute("token", userGetTokenResult.getToken());
				result.setAttribute("userId",userId);
				result.setAttribute("name",name);
				result.setAttribute("portraitUri",portraitUri);
				result.setAttribute("tokenType", "wechat");
			}else if(loginUser != null &&  loginUser.getId() != null) {
				//当前登录人ID
				String sfaId = loginUser.getId();

				//用户信息
				Map<String, Object> certTypeMap  = new HashMap<String, Object>();
				getUserInfo(sfaId,certTypeMap);
				String name = certTypeMap.get("nickname") != null?certTypeMap.get("nickname").toString():"";
				String uImage = certTypeMap.get("portraitUri") != null ?certTypeMap.get("portraitUri").toString():"";


				// 获取 Token 方法
				TokenResult userGetTokenResult = rongCloud.user.getToken(sfaId.toString(), name, uImage);
				
				System.out.println("rytoken2========================================================");
				System.out.println("rytoken:"+userGetTokenResult.getToken());
				System.out.println("sfaId:"+sfaId.toString());
				System.out.println("name:"+name);
				System.out.println("uImage:"+uImage);
				System.out.println(userGetTokenResult.getErrorMessage());
				
				logger.info(" ryToken getToken:  " + userGetTokenResult.toString());

				result.setAttribute("token", userGetTokenResult.getToken());
				result.setAttribute("userId",sfaId);
				result.setAttribute("name",name);
				result.setAttribute("portraitUri",uImage);
				result.setAttribute("tokenType", "user");
			}else {
				String sessionId =	request.getSession().getId();
				//session信息
				Map<String, Object> certTypeMap  = new HashMap<String, Object>();
				getSessionInfo(sessionId,certTypeMap);
				String name = certTypeMap.get("nickname").toString();
				String portraitUri = certTypeMap.get("portraitUri").toString();

				// 获取 Token 方法
				TokenResult userGetTokenResult = rongCloud.user.getToken(sessionId, name,portraitUri);
				
				System.out.println("rytoken3========================================================");
				System.out.println("rytoken:"+userGetTokenResult.getToken());
				System.out.println("portraitUri:"+portraitUri);
				System.out.println("name:"+name);
				System.out.println("sessionId:"+sessionId);
				System.out.println(userGetTokenResult.getErrorMessage());
				
				logger.info(" ryToken getToken:  " + userGetTokenResult.toString());
				result.setAttribute("name",name);
				result.setAttribute("portraitUri",portraitUri);
				result.setAttribute("token", userGetTokenResult.getToken());
				result.setAttribute("userId",sessionId);
				result.setAttribute("tokenType", "session");
			}
			if(result.getAttribute("token") == null){
				result.setStatusCode(ResultMap.STATUS_CODE_2023);
				result.setStatus(ResultMap.STATUS.FAILE);
				return result;
			}

			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			log.info(" ryToken end");

		}catch(Exception e){
			e.printStackTrace();
			log.error("error ryToken query :",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}

	/**
	 * 融云-生成回话列表  -wap 调用
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/rySessionList")
	@ResponseBody
	public ResultMap rySessionList(HttpServletRequest request, HttpServletResponse response,String conversationUsers){
		ResultMap result = new ResultMap();
		try{


			JSONArray array = JSONArray.parseArray(conversationUsers);
			Map<String, Object> certTypeMapS  = new HashMap<String, Object>();
			for (int i = 0; i < array.size(); i++) {
				JSONObject object =	array.getJSONObject(i);

				Map<String, Object> certTypeMap  = new HashMap<String, Object>();

				String userId = object.getString("id");
				if(StringUtils.isBlank(userId)){
					continue;
				}

				//获取用户信息
				getUserInfo(userId,certTypeMap);
				Object userIdForMap = certTypeMap.get("id");

				if(userIdForMap == null){
					//微信信息
					getWechatInfo(userId,certTypeMap);
				}

				certTypeMapS.put(userId,certTypeMap);

			}
			result.setAttribute("userInfos",certTypeMapS);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			log.info(" ryToken end");

		}catch(Exception e){
			log.error("error ryToken query :",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);

		}
		return result;
	}

	/**
	 * 融云-userInfo  -ios 调用
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/ryUserInfo")
	@ResponseBody
	public ResultMap ryUserInfo(HttpServletRequest request, HttpServletResponse response,String userId){

		ResultMap result = new ResultMap();

		try{

			Map<String, Object> certTypeMap  = new HashMap<String, Object>();

			//获取用户信息
			getUserInfo(userId,certTypeMap);
			Object userIdForMap = certTypeMap.get("id");

			if(userIdForMap == null){
				//微信信息
				Map wechatInfo = getWechatInfo(userId,certTypeMap);
			}

			if(certTypeMap.get("portraitUri") == null || StringUtils.isBlank(certTypeMap.get("portraitUri").toString())){
				certTypeMap.put("portraitUri",ctxPath + CommonConstantUtil.DEFUALTIMAGE);
			}

			result.setAttribute("userInfo",certTypeMap);
			result.setStatus(STATUS.SUCCESS);
			result.setStatusCode(ResultMap.STATUS_CODE_SUCCESS);

			log.info(" ryToken end");

		}catch(Exception e){
			log.error("error ryToken query :",e);
			result.setStatus(STATUS.ERROR);
			result.setStatusCode(ResultMap.STATUS_CODE_SYS_EXCEPTION);
		}
		return result;
	}
	public  Map  getUserInfo(String faId,Map<String, Object> certTypeMap) throws SQLException{

		FaUserDTO faUser = userService.getUserById(faId);

		if(faUser == null){
			return null;
		}
		
		//如果有店铺头像  取店铺头像
		ShopperUserInfoDTO shopperUserInfo=new ShopperUserInfoDTO();
		//用户id
		shopperUserInfo.setUserId(faId);
		ShopperUserInfoDTO dto = shopperUserInfoService.queryListGetFirst(shopperUserInfo);
		faUser.setuImage(dto.getUserHeadImg());
		
		//选择最优的图片  （上传 > 微信 >默认）
		String reg = "/upload/faUser/image/\\d+.png";
		if(StringUtils.isBlank(faUser.getuImage()) || faUser.getuImage().matches(reg)){
			if(faUser.getFaUserWechatDTO() != null && StringUtils.isNotBlank(faUser.getFaUserWechatDTO().getHeadimgurl())){
				faUser.setuImage(faUser.getFaUserWechatDTO().getHeadimgurl());
			}else{
				faUser.setuImage(CommonConstantUtil.DEFUALTIMAGE);
			}
		}

		String uImage = faUser.getuImage();

		if(uImage.indexOf("http") <0){
			uImage = ctxPath + uImage;
		}
		String name = faUser.getuLoginName();
		//用户名称    店铺名字》微信名》访客
		if(StringUtils.isNotBlank(dto.getUserName())){
			name = dto.getUserName();
		}else{
			if(faUser.getFaUserWechatDTO() != null && StringUtils.isNotBlank(faUser.getFaUserWechatDTO().getNickname())){
				name = faUser.getFaUserWechatDTO().getNickname();
			}
		}
		if (StringUtils.isBlank(name)){
			name = "访客";
		}
		
		certTypeMap.put("id",faId);
		certTypeMap.put("userId",faId);
		certTypeMap.put("nickname",name);
		certTypeMap.put("portraitUri",uImage);
		certTypeMap.put("tokenType","user");
		certTypeMap.put("userPhone",faUser.getuLoginName());
		if(StringUtils.isNotBlank(dto.getUserWechatNo())){//微信号 非空
			certTypeMap.put("userWechatNo",dto.getUserWechatNo());
		}

		logger.info(" ryToken  userId:"+faId);
		logger.info(" ryToken  name:"+name);
		logger.info(" ryToken  portraitUri:"+uImage);
		return  certTypeMap;
	}
	public  Map  getWechatInfo(String userId,Map<String, Object> certTypeMap)throws Exception{
		return getWechatInfo(userId,certTypeMap,false);
	}
	public  Map  getWechatInfo(String userId,Map<String, Object> certTypeMap,Boolean isQueryFriend) throws Exception{

		FaUserWechatDTO faUserWechatDTO = new FaUserWechatDTO();
		faUserWechatDTO.setMpOpenid(userId);
		FaUserWechatDTO view = userWehatService.queryUserWechatInfo(faUserWechatDTO);

		if(view != null) {

		    String imgUrl = "/64";
            String imgUrlRerurn = "";

		    if(StringUtils.isBlank(view.getHeadimgurl()) || imgUrl.equals(view.getHeadimgurl())){
                imgUrlRerurn = ctxPath+"/upload/faUser/image/1.png";
            }else{
                imgUrlRerurn = view.getHeadimgurl();
            }

			certTypeMap.put("id", userId);
			certTypeMap.put("nickname", StringUtils.isBlank(view.getNickname()) ? "微信理财师" : view.getNickname());
			certTypeMap.put("portraitUri", imgUrlRerurn);
			certTypeMap.put("tokenType", "wechat");
			if(StringUtils.isNotBlank(view.getUserId())){
				certTypeMap.put("wechatUserId", view.getUserId().toString());
			}
			if (isQueryFriend && SessionUtil.getSession().getLogin()){
				UserDTO user = SessionUtil.getSession().getUser();

				FpPhoneClientDTO fct = new FpPhoneClientDTO();
				fct.setUserId(user.getId());
				fct.setWeixinAppid(userId);
				//查询用户昵称+是否已经添加微信客户
				Map<String, String> queryWechatAndFlagAdd = fpPhoneClientService.queryWechatAndFlagAdd(fct);
				if (queryWechatAndFlagAdd != null && queryWechatAndFlagAdd.get("clientId") != null) {
					certTypeMap.put("tokenType", "wechat-friend");
				}

			}
		}else{
			// session 信息
			getSessionInfo(userId,certTypeMap);
		}
		return  certTypeMap;
	}

	public  Map  getSessionInfo(String userId,Map<String, Object> certTypeMap) throws Exception{

		certTypeMap.put("id",userId);
		certTypeMap.put("nickname","游客");
		certTypeMap.put("tokenType","session");
		certTypeMap.put("portraitUri",ctxPath+"/upload/faUser/image/1.png");

		return  certTypeMap;
	}
}